/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-11-15 20:07:00
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-11-17 13:59:48
 * @FilePath: /code/lesson34/udp_echo_server/UdpClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <string>
#include <arpa/inet.h>

void Usage(std::string proc)
{
    std::cout << "Usage:\t\n" << proc << " serverip serverport\n" << std::endl;
}

//客户端自己不显示绑定确定的端口号
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "socket err" << std::endl;
    }

    //服务器 ip + port
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    uint16_t port = std::stoi(argv[2]);
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);

    //先发后收
    while(true)
    {
        std::string message;
        std::cout << "Please Enter# ";
        getline(std::cin, message);

        //客户端主机的struct sockaddr_in
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server_addr, sizeof(server_addr));

        //服务器的struct sockaddr_in
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buf[1024];
        ssize_t n = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&peer, &len);
        if(n > 0)
        {
            buf[n] = 0;
            std::cout << "server echo# " << buf << std::endl;
        }
    }

    return 0;
}